package com.lft.juc06.subsidiary;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TestSemaphore {
	public static void main(String[] args) {
		// 线程数量：停车位，限流
		Semaphore semaphore = new Semaphore(3);
		for (int i = 1; i <= 6; i++) {
			new Thread(() -> {
				try {
					int time = (int) (Math.random() * 11);
					// acquire() 得到
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName() + " 抢到车位,准备停 " + time + " 秒");
					TimeUnit.SECONDS.sleep(time);
					System.out.println(Thread.currentThread().getName() + " 离开车位");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					// release() 释放
					semaphore.release();
				}
				
			}, String.valueOf(i)).start();
		}
	}
}
